#!/usr/bin/env python
# -*- coding: utf-8 -*-

from optparse import OptionParser

import httplib2
from amplee.utils import encode_slug

def post_article(collection, path, slug, verbose=False):
    h = httplib2.Http()
    body = file(path, 'rb').read()
    # Make it unicode
    slug = slug.decode('utf-8')
    # Encode it
    slug = encode_slug(slug, 'utf-8')
    r, c = h.request('http://localhost:8080/atom/%s' % collection, method='POST', body=body,
                     headers={'content-type': 'application/atom+xml', 'slug': slug})

    if verbose:
        print r
        print c

def parse_command_line():
    parser = OptionParser()
    parser.add_option("-c", "--collection", dest="collection",
                      help="name of the collection to this article to")
    parser.add_option("-s", "--slug", dest="slug",
                      help="slug when creating the resource")
    parser.add_option("-f", "--filepath", dest="filepath",
                      help="path to the file containing the raw article to be posted")
    parser.add_option("-v", "--verbose", action="store_true", default=False,
                      help="if used will display the response sent by the server")

    (options, args) = parser.parse_args()

    return options.collection, options.filepath, options.slug, options.verbose

if __name__ == '__main__':
    collection, path, slug, verbose = parse_command_line()
    post_article(collection, path, slug, verbose)
